import React, { useEffect, useState, useRef } from 'react';

//  ----------带回调的useCallBack--------------------
const useCallbackState = (od: any) => {
  const cbRef = useRef(); // 使用current来保存函数
  const [data, setData] = useState(od);

  // data变更时执行cb  或者不执行
  useEffect(() => {
    cbRef.current && cbRef.current(data);
  }, [data]);

  // 封装setData函数  最终返回
  const setStateCallBack = (newData: any, callback: Function) => {
    cbRef.current = callback;
    setData(newData);
  };

  return [data, setStateCallBack];
};

// --------第一次渲染不执行的useEffect------------
const useDidUpdateEffect = (fn: Function, inputs: any[]) => {
  const didMountRef = useRef(false);
  useEffect(() => {
    if (didMountRef.current) fn();
    else didMountRef.current = true;
  }, inputs);
};

export { useCallbackState, useDidUpdateEffect };
